﻿using Company.Shell.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using System.Windows.Controls;

namespace Company.Shell.Dialogs
{
    class DialogService : IDialogService
    {
        /// <summary>
        /// 弹出对话框
        /// </summary>
        /// <typeparam name="TView">用户控件</typeparam>
        /// <typeparam name="TViewModel">ViewModel</typeparam>
        /// <typeparam name="TResult">返回结果</typeparam>
        /// <param name="view"></param>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public async Task<DialogResult<TResult>> ShowDialogAsync<TView, TViewModel, TResult>(TView? view = null, TViewModel? viewModel = null)
            where TView : UserControl, new()
            where TViewModel : class
        {
            view ??= Activator.CreateInstance<TView>();
            viewModel ??= Activator.CreateInstance<TViewModel>();
            if(view is UserControl control)
            {
                view.DataContext = viewModel;
            }

            DialogWindow dialogWindow = new DialogWindow();
            dialogWindow.View = view;//用户控件
            dialogWindow.Width= view.Width;
            dialogWindow.Height= view.Height;

            var tcs = new TaskCompletionSource<DialogResult<TResult>>();
            dialogWindow.Closed += (s, e) =>
            {
                //todo
                var window = s as Window;
                var dialogViewModel = viewModel as IDialogViewModel<TResult>;
                var result = new DialogResult<TResult>(dialogViewModel);
                if (window != null)
                {
                    result.SetSuccess(window.DialogResult);
                }
                tcs.SetResult(result);
            };
            var vm = App.Current.Services.GetService<ShellViewModel>();
            if (vm != null)
            {
                vm.Show = Visibility.Visible;
                bool? result = dialogWindow.ShowDialog();
                vm.Show = Visibility.Collapsed;
            }
            else
            {
                bool? result = dialogWindow.ShowDialog();
            }
                return await tcs.Task;
        }
    }
}
